package com.kyh.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.kyh.util.redis.RedisUtil;

public class TokenUtil {
	private static final Logger logger = Logger.getLogger(TokenUtil.class);
	
	/**
	 * 获取用户ID
	 */
	public static Long getMerchantIdFromRedis(HttpServletRequest request) {
		// token格式userid_uuid
		String token = request.getHeader("auth_token");
		logger.info("header---auth_token------" + token);
		
		if (token == null || token.length() == 0) {
			return -1L;
		}
		Long merchantId = Long.parseLong(RedisUtil.getInstance().get(token, RedisUtil.KEY_ID));
		
		return merchantId;
	}
	
	/**
	 * 获取用户ID
	 */
	public static Long getMerchantIdFromRedisByToken(String authToken) {
		
		if (authToken == null || authToken.length() == 0) {
			return -1L;
		}
		
		String id_ = RedisUtil.getInstance().get(authToken, RedisUtil.KEY_ID);
		
		if (id_ == null || id_.length() == 0) {
			return -1L;
		}
		try {
			Long merchantId = Long.parseLong(RedisUtil.getInstance().get(authToken, RedisUtil.KEY_ID));
			return merchantId;
		} catch (Exception e) {
			return -1L;
		}
		
	}
	
	
	/**
	 * 获取用户ID
	 */
	public static Long getWapMerchantIdFromRedis(HttpServletRequest request) {
		String merchantId = null;
		Map<String, Cookie> cookieMap = saveCookieToMap(request);
		Cookie cookie = getCookieByName(cookieMap, ReqUtil.WAP_MERCHANT_TOKEN_ID);
		if (cookie != null) {
			merchantId = cookie.getValue();
		}
		if(CheckUtil.notNull(merchantId)) {
			return Long.parseLong(merchantId);
		}
		return null;
	}
	
	/**
	 * 从cookies中获取指定名字的cookie
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	private static Cookie getCookieByName(Map<String, Cookie> cookieMap, String name) {
		if (cookieMap.containsKey(name)) {
			Cookie cookie = (Cookie) cookieMap.get(name);
			return cookie;
		} else {
			return null;
		}
	}
	
	private static Map<String, Cookie> saveCookieToMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
	
}
